/*
    Dao Sqlite
    Copyright (C) 2010 Belousov Oleg <belousov.oleg@gmail.com>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include <sqlite3.h>
#include <dao.h>

static void db_exec(DaoContext *ctx, DValue *p[], int N) {
    sqlite3         *db = (sqlite3*) DaoCData_GetData(p[0]->v.cdata);
    char            *request = (char*) DString_GetMBS(p[1]->v.s);
    int             res;
    sqlite3_stmt    *stmt;

    res = sqlite3_prepare(db, request, -1, &stmt, NULL);

    if (res == SQLITE_OK) {
        DaoList     *list = DaoContext_PutList(ctx);
        int         ncol, col;

        ncol = sqlite3_column_count(stmt);
        res = sqlite3_step(stmt);

        while (res == SQLITE_ROW) {
            DValue  item;
            DMap    *map = DaoMap_New(0);

            for (col = 0; col < ncol; col++) {
                DString *str = NULL;

                int type = sqlite3_column_type(stmt, col);

                switch (type) {
                    case SQLITE_INTEGER:
                        item.t = DAO_INTEGER;
                        item.v.i = sqlite3_column_int(stmt, col);
                        break;

                    case SQLITE_FLOAT:
                        item.t = DAO_DOUBLE;
                        item.v.d = sqlite3_column_double(stmt, col);
                        break;

                    default:
                        str = DString_New(1);
                        DString_SetMBS(str, sqlite3_column_text(stmt, col));
                        item.t = DAO_STRING;
                        item.v.s = str;
                }

                DaoMap_InsertMBS(map, sqlite3_column_name(stmt, col), item);
                if (str) DString_Delete(str);
            }

            item.t = DAO_MAP;
            item.v.map = map;

            DaoList_Append(list, item);
            res = sqlite3_step(stmt);
        }
        sqlite3_finalize(stmt);
    } else {
        DaoContext_RaiseException(ctx, DAO_ERROR, sqlite3_errmsg(db));
    }
}

static DaoFuncItem dbMeth[] = {
    { db_exec, "exec(self:db, request:string) => list<any>" },
    { NULL, NULL }
};

DaoTypeBase dbTyper = {
    "db",
    NULL,
    NULL,           /* no constant number */
    dbMeth,         /* method */
    { NULL },       /* no parent type */
    NULL,
    NULL            /* free by free() */
};
